<template>
  <!--需求排期模块-->
  <basic-container>
    <beetles-search :size="'mini'" @search-form="searchForm" @empty-form="emptyForm" :expend="false">
      <div class="beetles-search-from" :style="{height:searchConceal? 'auto' :'40px'}" style="overflow:hidden"
           slot-scope="{searchConceal}"
           slot="searchForm">
        <el-form ref="form" :model="queryForm" :inline="true" label-width="100px"
                 @submit.native.prevent>
          <!--<el-form-item label="需求ID:">-->
          <!--  <el-input-->
          <!--    placeholder="请输入内容"-->
          <!--    v-model="queryForm.shortId"-->
          <!--    size="mini"-->
          <!--    clearable-->
          <!--    @clear="searchForm">-->
          <!--  </el-input>-->
          <!--</el-form-item>-->
          <el-form-item label="订单:">
            <el-select id="id-business-creativerequestbc-isShowSelectOptions" v-model="queryForm.offerId" clearable
                       filterable size="mini" placeholder="请选择订单"
                       ref="creativeOfferId" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in offerList"
                :key="item.value"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="媒体:">
            <el-select id="id-business-creativerequestbc-isShowSelectOptions" v-model="queryForm.platform" clearable
                       size="mini" placeholder="请选择媒体"
                       ref="creativePlatform" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in platformList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设计师:">
            <el-select id="id-business-creativerequestbc-queryForm-designers" v-model="queryForm.designers" clearable
                       filterable size="mini" placeholder="请选择设计师"
                       ref="creativeDesigners" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in allDesignerList"
                :key="item.value"
                :label="item.realName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需求ID">
            <el-input
              placeholder="请输入内容"
              v-model="queryForm.strShortId"
              size="mini"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="需求名称">
            <el-input
              placeholder="请输入内容"
              v-model="queryForm.name"
              size="mini"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="需求方:">
            <el-select id="id-business-creativerequestbc-queryForm-requester" v-model="queryForm.requester" clearable
                       filterable size="mini"
                       placeholder="请选择需求方" @change="searchForm">
              <el-option
                v-for="item in requesterList"
                :key="item.id"
                :label="item.realName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="素材类型:">
            <el-select id="id-business-creativerequestbc-queryForm-creativeType" v-model="queryForm.creativeType"
                       clearable size="mini" placeholder="请选择素材类型"
                       ref="autoAuditCreativeType" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in createdType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度:">
            <el-select id="id-business-creativerequestbc-queryForm-urgency" v-model="queryForm.urgency" clearable
                       size="mini" placeholder="请选择紧急程度"
                       ref="creativeUrgency" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in urgencyList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="制作状态:">
            <el-select id="id-business-creativerequestbc-queryForm-status" v-model="queryForm.status" clearable
                       size="mini" placeholder="请选择制作状态"
                       ref="creativeStatus" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in makingStatus"
                v-if="userInfo.detail.tenantVariables['ENABLE_REQUEST_DETAIL_AUDIT'] == 'true' || (item.value != 4 && item.value != 5)"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态:">
            <el-select id="id-business-creativerequestbc-queryForm-autoAuditStatus" v-model="queryForm.autoAuditStatus"
                       clearable size="mini" placeholder="请选择审核状态"
                       ref="creativeAutoAuditStatus" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in auditStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排期:">
            <el-select id="id-business-creativerequestbc-queryForm-scheduleStatus" v-model="queryForm.scheduleStatus"
                       clearable size="mini" placeholder="请选择排期状态"
                       ref="scheduleStatus" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in scheduleStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间:">
            <el-date-picker
              v-model="submissionTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="lastPickerOptions"
              style="width: 70%"
              @change="searchForm">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="排期时间:">
            <el-date-picker
              id="id-business-creativerequestbc-scheduleDateList"
              v-model="scheduleDateList"
              type="daterange"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              style="width: 70%"
              @change="searchForm">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </beetles-search>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :view-name="'creativerequestbc'"
               :before-open="beforeOpen"
               :row-class-name-rollback="getRowClassName"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @search-reset="searchReset"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad"
               @selection-change="handleSelectionChange">
      <template v-slot:menuLeft>
        <el-button type="primary" icon="el-icon-check" size="mini" plain @click="multipleComplete">批量完成</el-button>
        <el-button type="warning" icon="el-icon-close" size="mini" plain @click="multipleClose">批量关闭</el-button>
      </template>
      <template slot-scope="{row}" slot="offerId">
        <el-tooltip effect="dark" :content="row.offerName" placement="top">
          <div class="over-flow" v-if="row.status !== 9">
            <a href="javascript:void(0)" @click="openOcPage(row,'creativeRequest')">{{ row.offerName }}</a>
          </div>
          <div class="over-flow" v-else>
            {{ row.offerName }}
          </div>
        </el-tooltip>
      </template>
      <template slot-scope="{row}" slot="name">
        <el-tooltip effect="dark" :content="row.name" placement="top">
          <div class="over-flow" v-if="row.status !== 9 && showEdit(row)">
            <a href="javascript:void(0)" @click="openOcPage(row,'editCreativeRequest')">{{ row.name }}</a>
          </div>
          <div class="over-flow" v-else>
            {{ row.name }}
          </div>
        </el-tooltip>
      </template>
      <template slot-scope="{row}" slot="content">
        <div>{{ htmlToString(row.content) }}</div>
      </template>
      <template slot-scope="{row}" slot="platform">
        <div style="display: flex;flex-wrap: wrap;">
          <div style="width: 20px;margin-right: 4px"
               v-for="(item,index) in platformLogo(row.platform)"
               :key="index">
            <img style="width: 100%" :src="item.url" :title="item.name">
          </div>
        </div>
      </template>
      <template slot-scope="{row}" slot="finishedCreativeNum">
        {{ row.finishedCreativeNum + "/" }}&nbsp;
        <i class="el-icon-video-camera">{{ row.finishedCreativeVideoNum }}&nbsp;/&nbsp;&nbsp;</i>
        <i class="el-icon-camera">{{ row.finishedCreativeImageNum }}</i>
      </template>
      <template slot-scope="{row}" slot="requesterName">
        <div>
          <el-tag type="mini">{{ row.requesterName }}</el-tag>
        </div>
      </template>
      <template slot-scope="{row}" slot="prodMakeTime">
        <div>{{ getViewMakeTime(row.prodMakeTime) }}</div>
      </template>
      <template slot-scope="{row}" slot="scheduleDate">
        <el-tooltip effect="dark" :content="getScheduleDateTooltip(row)" placement="top"
                    :disabled="getScheduleDateTooltip(row) == ''">
          <!--          <div :style="getScheduleDateStyle(row)">{{ (row.scheduleStatus == 1) ? '未排期' : row.scheduleDate }}</div>-->
          <div :style="getScheduleDateStyle(row)">{{ getScheduleDate(row) }}</div>
        </el-tooltip>
      </template>
      <template slot-scope="{row}" slot="urgency">
        <!--<div>-->
        <!--  <el-select id="id-business-creativerequestbc-row-urgency" v-model="row.urgency" size="mini" class="form_item"-->
        <!--             @change="urgencyChanged(row)" :disabled="row.status === 9 || !(userRole.admin)">-->
        <!--    <el-option v-for="(item) in urgencyList" :key="item.value" :value="item.value"-->
        <!--               :label="item.label">-->
        <!--    </el-option>-->
        <!--  </el-select>-->
        <!--</div>-->
        <el-tag
          v-if="row.urgency === 0"
          type="info"
          size="mini"
          effect="dark">
          一般
        </el-tag>
        <el-tag
          v-else
          type="danger"
          size="mini"
          effect="dark">
          紧急
        </el-tag>
      </template>
      <template slot-scope="{row}" slot="designersList">
        <!--<div>-->
        <!--  <el-select id="id-business-creativerequestbc-row-designersList" multiple filterable-->
        <!--             v-model="row.designersList" size="mini" class="form_item" @change="designersChanged(row)"-->
        <!--             :disabled="row.status === 9 || !(userRole.admin || userInfo.user_id == row.designerManager)">-->
        <!--    <el-option v-for="(item) in allUserList"-->
        <!--               v-if="(item.roleAlias.split(',').includes('designer') && item.status == 1 && item.isDeleted == 0) || row.designersList.includes(item.id)"-->
        <!--               :key="item.id" :value="item.id"-->
        <!--               :disabled="!(item.roleAlias.split(',').includes('designer') && item.status == 1 && item.isDeleted == 0)"-->
        <!--               :label="item.realName">-->
        <!--    </el-option>-->
        <!--  </el-select>-->
        <!--</div>-->
        <el-tooltip effect="dark" :content="findDesigners(row.designersList)" placement="top">
          <span class="over-flow">{{ findDesigners(row.designersList) }}</span>
        </el-tooltip>
      </template>
      <template slot-scope="{row}" slot="creativeType">
        <div>
          <el-tag type="mini" v-if="row.creativeType.indexOf('0') > -1">图片</el-tag>
          <el-tag type="mini" v-if="row.creativeType.indexOf('1') > -1">视频</el-tag>
        </div>
      </template>
      <template slot-scope="{type,size,row}" slot="menu">
        <el-tooltip content="查看" placement="top">
          <el-button size="small" icon="el-icon-view" type="text" @click="handleCheck(row)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="上传" placement="top">
          <el-button icon="el-icon-upload2" type="text" @click="openOcPage(row,'uploadCreativeRequest')"
                     :disabled="!(userRole.designer && [1,2,3].includes(row.status)) || row.demandStatus===1"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="排期/分配" placement="top">
          <el-button icon="el-icon-edit" type="text" @click="openDistributionDrawer(row)"
                     :disabled="!(row.scheduleStatus != 2 && (roles.designer_manager || roles.admin)) || row.demandStatus===1"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="完成" placement="top">
          <el-button icon="el-icon-check" type="text" @click="handleFinish(row)"
                     :disabled="!(row.scheduleStatus == 0 && (row.designersList.includes(userInfo.user_id) || roles.designer_manager || roles.admin)) || row.demandStatus===1"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="激活" placement="top">
          <el-button :disabled="row.demandStatus===0" icon="el-icon-switch-button" type="text"
                     @click="handleOpen(row)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="关闭" placement="top">
          <el-button :disabled="row.demandStatus===1" icon="el-icon-close" type="text"
                     @click="handleClose(row)"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>

    <div v-if="dialogOpen">
      <request-dialog :requestid="dialogCreativeRequestId" :title="dialogType" :dialogVisible="dialogOpen"
                      :offerId="dialogOfferId" :dataList="dataList" :userRole="userRole" :offerInfo="dialogOfferInfo"
                      @close-dialog="closeDialog"></request-dialog>
    </div>

    <!--<div>-->
    <!--  <el-dialog :visible.sync="scheduleDateDialog.visible" :modal-append-to-body="false"-->
    <!--             :title="(scheduleDateDialog.creativeRequest == null)?'':scheduleDateDialog.creativeRequest.name"-->
    <!--             :close-on-click-modal="false" :before-close="handleClose" :append-to-body="true" width="20%">-->
    <!--    <div>-->
    <!--      <div class="text" style="width: 15%">排期:</div>-->
    <!--      <el-date-picker-->
    <!--        id="id-business-creativerequestbc-scheduleDateDialog-scheduleDate"-->
    <!--        v-model="scheduleDateDialog.scheduleDate"-->
    <!--        ref="scheduleDateDialog"-->
    <!--        type="date"-->
    <!--        value-format="yyyy-MM-dd"-->
    <!--        unlink-panels-->
    <!--        size="mini"-->
    <!--        :picker-options="futurePickerOptions"-->
    <!--        placeholder="请输入排期时间"-->
    <!--        style="width: 70%">-->
    <!--      </el-date-picker>-->
    <!--    </div>-->
    <!--    <div style="height: 20px;"></div>-->
    <!--    <div style="text-align: center;">-->
    <!--      <span>-->
    <!--        <el-button id="id-business-creativerequestbc-handleScheduleDateUpdate" icon="el-icon-check"-->
    <!--                   :size="mini" type="primary"-->
    <!--                   :disabled="(scheduleDateDialog.scheduleDate == null || scheduleDateDialog.scheduleDate == '')"-->
    <!--                   plain @click="handleScheduleDateUpdate(scheduleDateDialog.creativeRequest)">确 定</el-button>-->
    <!--      </span>-->
    <!--      <span style="width: 30px"></span>-->
    <!--      <span>-->
    <!--        <el-button id="id-business-creativerequestbc-handleScheduleDateClose" icon="el-icon-close"-->
    <!--                   :size="mini" plain @click="handleScheduleDateClose()">返 回</el-button>-->
    <!--      </span>-->
    <!--    </div>-->
    <!--  </el-dialog>-->
    <!--</div>-->
    <!--新版排期-->
    <el-drawer
      title="排期/分配"
      size="40%"
      :visible.sync="distributionDrawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      ref="drawer"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <el-form class="distribution-form" ref="distributionFormRef" :model="distributionForm" label-width="80px"
                 :rules="distributionFormRules">
          <el-form-item label="名称">
            <el-input v-model="distributionForm.name" size="mini" disabled></el-input>
          </el-form-item>
          <el-form-item label="设计师" prop="designersList">
            <el-select multiple filterable clearable
                       v-model="distributionForm.designersList" size="mini">
              <el-option v-for="(item) in allUserList"
                         v-if="(item.roleAlias.split(',').includes('designer') && item.status == 1 && item.isDeleted == 0) || distributionForm.designersList.includes(item.id)"
                         :key="item.id"
                         :value="item.id"
                         :disabled="!(item.roleAlias.split(',').includes('designer') && item.status == 1 && item.isDeleted == 0)"
                         :label="item.realName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度" prop="urgency">
            <el-select v-model="distributionForm.urgency" size="mini">
              <el-option v-for="(item) in urgencyList" :key="item.value" :value="item.value"
                         :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排期时间" prop="scheduleDate">
            <el-date-picker
              v-model="distributionForm.scheduleDate"
              type="date"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              :picker-options="futurePickerOptions"
              placeholder="请输入排期时间"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <template slot="bottom">
          <el-button type="primary" size="mini" @click="submitDistributionForm" :disabled="SubmitDistributionLoading">
            保存
          </el-button>
          <el-button size="mini" @click="distributionDrawer=false">取消</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>
    <div newPageLink></div>
  </basic-container>
</template>

<script>
import {getOfferOptimizer as getOptimizer, updateDemandStatusToCloseByBatch} from "@/api/offer/creativerequest";
import {
  getList,
  getDetail,
  getUserRole,
  updateDesigner,
  updateUrgency,
  getRequestUserList,
  getDesignerSelect,
  updateScheduleStatus,
  updateScheduleDate,
  updateRequsetSchedule,
  updateScheduleStatusToDoneByBatch,
  updateDemandStatusToActivateByBatch
} from "@/api/offer/creativerequest";
import {loadBcCreativeRequestInfo} from "@/api/business/offer";
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {getAllUser} from "@/api/user"
import {OC_LOGIN_URL} from "@/const/urlConst"
import {getToken} from '@/util/auth';
import {genTokenKey} from '@/api/user';
import website from "@/config/website";
import {createWebSocket} from "@/util/ws";
import {mapGetters} from "vuex";
import requestDialog from "@/views/offer/components/request-dialog"
import Moment from 'moment'
import {transformObjectList, findObject, deepClone} from "@/util/util";
import {getSysDictList} from "@/api/system/dict";
import BeetlesTable from "@/components/basic-components/beetles-table";
import {platformLogo} from "@/util/beetles";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import beetlesSearch from "@/components/basic-components/beetles-search"
import {removeTimingReportByIds} from "@/api/system/timing-report-config";

export default {
  components: {
    BeetlesTable,
    requestDialog,
    CsDrawerContainer,
    beetlesSearch
  },
  data() {
    return {
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      userRole: {
        designer: true,
        optimize: true,
        admin: true
      },//用户角色
      loadInitParams: false,
      form: {},
      queryForm: {
        offerId: null,    //订单名称
        platform: null,      //媒体
        status: null,        //制作状态
        autoAuditStatus: null,   //审核状态
        creativeType: null,     //素材类型
        urgency: null,       //紧急程度
        designers: null,      //设计师
        requester: null,     //需求方
        beginDate: null,
        endDate: null,
        scheduleDateList: '',
        scheduleStatus: '',
        strShortId: '',//需求ID
        name: null, // 需求名称
      },
      submissionTime: [],
      scheduleDateList: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近两周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
            picker.$emit('pick', [start, end]);
          }
        },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '所有',
            onClick(picker) {
              const end = "";
              const start = "";
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      lastPickerOptions: {
        disabledDate(time) {
          return time.getTime() >= Date.now();
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近两周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
            picker.$emit('pick', [start, end]);
          }
        },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '所有',
            onClick(picker) {
              const end = "";
              const start = "";
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      futurePickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Moment(Date.now()).subtract(1, 'days').toDate();
        },
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      dataList: '',
      dialogType: '', //弹窗类型
      dialogOpen: false, //弹窗是否打开
      dialogOfferInfo: null,
      dialogOfferId: null,
      dialogCreativeRequestId: null,
      makingStatus: [
        {label: '需求待审核', value: 4},
        {label: '需求已拒绝', value: 5},
        {label: '待分配', value: 0},
        {label: '制作中', value: 1},
        {label: '待确认', value: 2},
        {label: '已确认', value: 3},
        {label: '已删除', value: 9},
      ],
      auditStatus: [
        {label: '待审核', value: 0},
        {label: '审核完成', value: 2},
        {label: '全部拒绝', value: 3},
        {label: '部分通过', value: 5},
      ],
      scheduleStatusList: [
        {label: '已排期', value: 0},
        {label: '未排期', value: 1},
        {label: '已完成', value: 2},
        {label: '已关闭', value: 3},
      ],
      createdType: [
        {label: '图片', value: '0'},
        {label: '视频', value: '1'},
      ],
      urgencyList: [
        {label: '一般', value: 0},
        {label: '紧急', value: 1},
      ],
      option: {
        // height:'auto',
        selection: true,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        menuWidth: 170,
        searchMenuSpan: 6,
        delBtn: false,
        editBtn: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "需求ID",
            prop: "shortId",
            overHidden: true,
          },
          {
            label: "排期",
            prop: "scheduleDate",
            width: 85
          },
          {
            label: "订单",
            prop: "offerId",
            type: 'select',
            dataType: 'string',
            dicData: [],
            props: {
              label: "name",
              value: "id"
            },
            searchFilterable: true,
          },
          {
            label: "名称",
            prop: "name",
            viewDisplay: false,
            overHidden: true
          },
          {
            label: "媒体",
            prop: "platform",
            // multiple: true,
            // type: 'select',
            // dataType: 'string',
            // dicData: [
            //   {'dictKey': 'facebook', 'dictValue': 'Facebook'},
            //   {'dictKey': 'google', 'dictValue': 'Google'},
            //   {'dictKey': 'bigo', 'dictValue': 'Bigo'},
            //   {'dictKey': 'tiktok', 'dictValue': 'TikTok'}
            // ],
            // props: {
            //   label: "dictValue",
            //   value: "dictKey"
            // },
            // searchMultiple: true,
            // rules: [{
            //   required: true,
            //   message: "请输入媒体",
            //   trigger: "blur"
            // }],
          },
          {
            label: "需求内容",
            prop: "content",
            rules: [{
              required: true,
              message: "请输入需求内容",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: '需求数量',
            prop: 'creativeNum',
          }, {
            label: '上传数量/视频/图片',
            prop: 'finishedCreativeNum',
            width: 130
          }, {
            label: '制作时间',
            prop: 'prodMakeTime',
            slot: true,
          },
          {
            label: "制作状态",
            prop: "status",
            dicData: [
              {label: '需求待审核', value: 4},
              {label: '需求已拒绝', value: 5},
              {label: '待分配', value: 0},
              {label: '制作中', value: 1},
              {label: '待确认', value: 2},
              {label: '已确认', value: 3},
              {label: '已删除', value: 9},
            ],
            type: 'select',
          },
          {
            label: "审核状态",
            prop: "autoAuditStatus",
            dicData: [
              {label: '待审核', value: 0},
              {label: '审核完成', value: 2},
              {label: '全部拒绝', value: 3},
              {label: '部分通过', value: 5},
            ],
            type: 'select',
          },
          {
            label: "素材类型",
            prop: "creativeType",
            dicData: [
              {label: '图片', value: '0'},
              {label: '视频', value: '1'},
            ],
            type: 'select',
          },
          {
            label: "紧急程度",
            prop: "urgency",
            dicData: [
              {label: '一般', value: 0},
              {label: '紧急', value: 1},
            ],
            type: 'select',
          },
          {
            label: "需求方",
            prop: "requesterName",
            slot: true,
          },
          {
            label: "设计师",
            prop: "designersList",
            width: 120,
            rules: [{
              required: false,
              message: "请输入设计师",
              trigger: "blur"
            }],
            type: 'select',
            multiple: true,
            dataType: 'string',
            slot: true,
            overHidden: true
          },
          {
            label: "创建时间",
            prop: "createTime",
            overHidden: true,
          },
          {
            label: "最新上传时间",
            prop: "uploadTime",
            width: 100,
            overHidden: true,
          },
          {
            label: "优化师验收时间",
            prop: "auditTime",
            width: 120,
            overHidden: true,
          },
        ]
      },
      data: [],
      currOpRowId: '',
      designerList: [],
      isContain: false,
      offerList: [],
      designerUserList: [],
      requesterList: [],      // 优化师列表
      allUserList: [],      //所有用户
      platformList: [],
      allDesignerList: [],
      scheduleDateDialog: {
        visible: false,
        creativeRequest: null,
        scheduleDate: '',
      },
      // marco
      // 排期弹窗
      distributionDrawer: false,
      distributionForm: {
        name: '',
        designersList: [],
        urgency: 0,
        scheduleDate: ''
      },
      SubmitDistributionLoading: false,
      distributionFormRules: {
        designersList: [
          {type: 'array', required: true, message: '请至少选择一个设计师', trigger: 'change'}
        ],
        urgency: [
          {required: true, message: '请选择紧急程度', trigger: 'change'}
        ],
        scheduleDate: [
          {required: true, message: '请选择排期时间', trigger: 'change'}
        ]
      },
      // marco
      // 多选
      multipleSelection: [],
      multipleSelectionId: []
    };
  },
  created() {
    getSysDictList('platforms').then(map => {
      this.platformList = map['platforms'];
      let column = findObject(this.option.column, 'platform', 'prop')
      if (column != null) {
        column.dicData = map['platforms'];
      }
    });
    getAllUser({statusList: '0,1,2', isAll: true}).then(res => {
      this.allUserList = res.data.data;
    });
    this.buildSearch();
  },
  mounted() {
    loadBcCreativeRequestInfo({offerType: 'admin,owner,manager,shared'}).then(res => {
      this.offerList = res.data.data.offerList;
      this.designerUserList = res.data.data.designerUserList;
      let distinctUserIdSet = [];
      let distinctDesignerUserList = [];
      this.designerUserList.forEach((u) => {
        if (!distinctUserIdSet.includes(u.userId)) {
          distinctUserIdSet.push(u.userId);
          distinctDesignerUserList.push(u);
        }
      })
      for (let i = 0; i < this.option.column.length; i++) {
        if (this.option.column[i].prop == 'designers') {
          this.option.column[i].dicData = distinctDesignerUserList;
        }
        if (this.option.column[i].prop == 'offerId') {
          this.option.column[i].dicData = this.offerList;
        }
      }
    })
    getUserRole().then(res => {
      let roleList = res.data.data.split(',');
      this.userRole.designerManager = roleList.includes('designer_manager') || roleList.includes('admin');
      this.userRole.designer = roleList.includes('designer') || roleList.includes('admin') || roleList.includes('designer_manager');
      this.userRole.optimize = roleList.includes('optimizer') || roleList.includes('admin');
      this.userRole.admin = roleList.includes('admin');
    })

    let self = this;
    self.isRefreshing = false;
    if (!self.socket) {
      self.socket = createWebSocket('/api/blade-system/wss', 'json');
      if (self.socket) self.socket.ontextmessage = (msg) => {
        let msgObj = JSON.parse(msg);
        //console.log("socket receive:" + msg)
        if (msgObj) {
          if (!self.isRefreshing && msgObj.messageName === 'tenantMessage' && msgObj.data.messageName === 'creativeRequestChanged') {
            if (msgObj.data.creativeRequestIds != null) {
              let creativeRequestIdList = msgObj.data.creativeRequestIds.split(",");
              if (self.data.find((v) => {
                if (self.excludeRefreshedIds != null && self.excludeRefreshedIds.includes(v.id)) {
                  self.excludeRefreshedIds.splice(self.excludeRefreshedIds.indexOf(v.id), 1);
                  return false;
                }
                return creativeRequestIdList.includes(v.id);
              }) == null) {
                return;
              }
            }
            self.isRefreshing = true;
            //不可以频繁刷新，如果有刷新需求，延迟5秒刷新，在延迟期间，有新的刷新需求均不会多次触发onLoad
            setTimeout(() => {
              self.onLoad(self.page);
              self.isRefreshing = false;
            }, 5000);
          }
        }
      };
      if (self.socket) self.socket.onerror = () => {
        this.$message({
          type: 'warning',
          message: '您的网络目前不稳定，数据可能不能自动刷新！'
        });
      };
    }
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if (self.socket) {
      self.socket.close();
      self.socket = null;
    }
    next();
  },
  computed: {
    ...mapGetters(["permission", "userInfo", "roles"]),
  },
  methods: {
    async loadDesignerList() {
      await getRequestUserList('', '', 'designer').then(res => {
        this.allDesignerList = res.data.data;
      });
    },
    async loadRequesterList() {
      await getRequestUserList('', '', 'requester').then(res => {
        this.requesterList = res.data.data;
      });
    },
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    isShowSelectOptions(isShowSelectOptions) {
      if (!isShowSelectOptions) this.$refs.creativeOfferId.blur();
      if (!isShowSelectOptions) this.$refs.creativePlatform.blur();
      if (!isShowSelectOptions) this.$refs.creativeStatus.blur();
      if (!isShowSelectOptions) this.$refs.creativeAutoAuditStatus.blur();
      if (!isShowSelectOptions) this.$refs.autoAuditCreativeType.blur();
      if (!isShowSelectOptions) this.$refs.creativeUrgency.blur();
      if (!isShowSelectOptions) this.$refs.creativeDesigners.blur();
    },
    buildSearch() {
      let query = {...this.queryForm};

      if (this.submissionTime != null) {
        query.beginDate = this.submissionTime[0];
        query.endDate = this.submissionTime[1];
      } else {
        query.beginDate = "";
        query.endDate = "";
      }
      if (this.scheduleDateList == null || this.scheduleDateList.length != 2) {
        query.scheduleDateList = '';
      } else {
        query.scheduleDateList = this.scheduleDateList.join(',');
      }
      this.query = query;
    },
    //搜索按钮函数
    searchForm() {
      this.buildSearch();
      this.page.currentPage = 1
      this.onLoad(this.page)
    },
    //清空按钮函数
    emptyForm() {
      this.queryForm = {
        offerId: null,    //订单名称
        platform: null,      //媒体
        status: null,        //制作状态
        autoAuditStatus: null,   //审核状态
        creativeType: null,     //素材类型
        urgency: null,       //紧急程度
        designers: null,      //设计师
        requester: null,     //需求方
        beginDate: null,
        endDate: null,
        scheduleDateList: '',
        scheduleStatus: '',
      }
      this.submissionTime = null
      this.scheduleDateList = [];
      this.searchForm();
    },
    getTokenKeyInfo(row, type) {
      if (type == 'creativeRequest') {
        return JSON.stringify({offerId: row.offerId, r: '/creativerequest'});
      }
      if (type == 'editCreativeRequest') {
        return JSON.stringify({
          offerId: row.offerId,
          r: '/creativerequest',
          ropList: [{rid: row.id, rop: 'editCreativeRequest'}]
        });
      }
      if (type == 'uploadCreativeRequest') {
        return JSON.stringify({
          offerId: row.offerId,
          r: '/creativerequest',
          ropList: [{rid: row.id, rop: 'uploadCreativeRequest'}]
        });
      }
      return '';
    },
    openOcPage(row, type) {
      let ocTokenKey = '';
      let headers = {};
      headers[website.tokenHeader] = getToken();
      genTokenKey({
        sync: true,
        headers: headers,
        info: this.getTokenKeyInfo(row, type),
        success: (data) => {
          ocTokenKey = data.tokenKey;
        },
        error: () => {
        }
      });
      if (ocTokenKey == '') {
        this.$message.error('获取信息错误，无法正确跳转到订单中心');
        return;
      }
      let eleList = document.querySelectorAll('div[newPageLink]');
      let content = eleList[0];
      let linkEle = document.createElement("a");
      content.appendChild(linkEle);

      // 利用URL.createObjectURL()方法为a元素生成blob URL
      linkEle.target = '_blank';
      linkEle.href = OC_LOGIN_URL + '?tokenKey=' + ocTokenKey;
      linkEle.click();
      linkEle.remove();
    },
    getViewMakeTime(makeTime) {
      if (makeTime == 0) {
        return '无';
      }
      let minutes = Math.floor(makeTime / 60) % 60;
      let hours = Math.floor(makeTime / 3600);
      return ((hours == 0) ? '' : (hours + '小时')) + ((minutes == 0) ? '' : (minutes + '分钟'));
    },
    showEdit(row) {
      if (this.userRole.admin || this.userRole.optimize || this.userRole.designerManager || row.designerManager === this.userInfo.user_id) {
        return true
      } else if (this.userRole.designer && row.designers != null) {
        if (row.designers.split(',').includes(this.userInfo.user_id)) {
          return true;
        }
      }
      return false;
    },
    contentOmit(val) {
      if (val.length > 10) {
        return val.substring(0, 9) + '....'
      } else {
        return val
      }
    },
    getOfferName(row) {
      for (let i = 0; i < this.offerList.length; i++) {
        if (row.offerId == this.offerList[i].id) {
          return this.offerList[i].name;
        }
      }
      return row.offerId;
    },
    urgencyChanged(row) {
      if (this.excludeRefreshedIds == null) {
        this.excludeRefreshedIds = [];
      }
      if (!this.excludeRefreshedIds.includes(row.id)) {
        this.excludeRefreshedIds.push(row.id);
      }

      updateUrgency(row.id, row.urgency).then(res => {
        if (!res.data.success) {
          this.$message({
            type: 'warning',
            message: '操作失败！'
          });
          this.excludeRefreshedIds.splice(this.excludeRefreshedIds.indexOf(row.id), 1);
        }
      });
    },
    designersChanged(row) {
      if (row.designersList.length == 0) {
        this.$message({
          type: 'warning',
          message: '不可以清空设计师分配列表！'
        });
        setTimeout(() => {
          row.designersList = row.designers.split(",");
        }, 10)
        return;
      }
      let designers = row.designersList.join(',');

      if (this.excludeRefreshedIds == null) {
        this.excludeRefreshedIds = [];
      }
      if (!this.excludeRefreshedIds.includes(row.id)) {
        this.excludeRefreshedIds.push(row.id);
      }
      updateDesigner(row.id, designers).then(res => {
        if (!res.data.success) {
          this.$message({
            type: 'warning',
            message: '操作失败！'
          });
          this.excludeRefreshedIds.splice(this.excludeRefreshedIds.indexOf(row.id), 1);
        } else {
          row.designers = designers;
          if (row.status == 0 || row.status == 1) {
            row.status = (row.designersList.length == 0) ? 0 : 1;
          }
        }
      });
    },
    //查看
    handleCheck(row) {
      console.log(row);
      console.log(this.userRole);
      this.currOpRowId = row.id;
      getDetail(row.id).then(res => {
        this.dataList = res.data.data
        this.dialogCreativeRequestId = row.id;
        this.dialogOfferId = row.offerId;
        this.dialogType = 'check';
        if (this.dialogOfferInfo == null || this.dialogOfferInfo.id != row.offerId) {
          getOfferDetail(row.offerId).then(res => {
            this.dialogOfferInfo = res.data.data;
            this.dialogOpen = true;
          });
        } else {
          this.dialogOpen = true;
        }
      })
    },
    handleScheduleDate(row) {
      this.scheduleDateDialog.creativeRequest = row;
      this.scheduleDateDialog.scheduleDate = row.scheduleDate;
      this.scheduleDateDialog.visible = true;
      this.$nextTick(() => {
        this.$refs.scheduleDateDialog.focus();
      });
    },
    handleScheduleDateUpdate(row) {
      updateScheduleDate({id: row.id, scheduleDate: this.scheduleDateDialog.scheduleDate}).then(res => {
        if (res.data.success) {
          this.$message.success('需求排期设置成功');
          // row.scheduleStatus = 0;
          // row.scheduleDate = this.scheduleDateDialog.scheduleDate;
          this.refreshChange();
          this.scheduleDateDialog.visible = false;
        }
      });
    },
    handleScheduleDateClose() {
      this.scheduleDateDialog.visible = false;
    },
    getScheduleDateStyle(row) {
      if (row.scheduleStatus == 2) {
        return 'color: green;';
      } else if (row.scheduleStatus == 0) {
        if (row.scheduleDate < Moment(new Date()).format('YYYY-MM-DD')) {
          return 'color: red;';
        }
      }
      return 'color: black;';
    },
    getScheduleDateTooltip(row) {
      if (row.scheduleStatus == 2) {
        return '需求已完成';
      } else if (row.scheduleStatus == 0) {
        if (row.scheduleDate < Moment(new Date()).format('YYYY-MM-DD')) {
          return '需求已超期';
        }
      }
      return '';
    },

    getScheduleDate(row) {
      if (row.demandStatus === 1) {
        return '已关闭'
      } else {
        if (row.scheduleStatus === 1) {
          return '未排期'
        } else {
          return row.scheduleDate
        }
      }
    },

    handleFinish(row) {
      this.$confirm('请确认是否完成当前需求', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateScheduleStatus({id: row.id}).then(res => {
          if (res.data.success) {
            this.$message.success('需求排期已设置完成');
            // row.scheduleStatus = 2;
            this.refreshChange();
          }
        });
      });
    },
    handleClose(row) {
      let arr = []
      arr.push(row.id)
      console.log(arr)
      this.$confirm('请确认是否关闭当前需求', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateDemandStatusToCloseByBatch(arr).then(res => {
          if (res.data.success) {
            this.$message.success('已关闭');
            // row.scheduleStatus = 2;
            this.refreshChange();
          }
        });
      });

    },
    handleOpen(row) {
      let arr = []
      arr.push(row.id)
      console.log(arr)
      this.$confirm('请确认是否激活当前需求', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateDemandStatusToActivateByBatch(arr).then(res => {
          if (res.data.success) {
            this.$message.success('已激活');
            // row.scheduleStatus = 2;
            this.refreshChange();
          }
        });
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },

    //dialog关闭回调
    closeDialog() {
      this.dialogOpen = false
    },
    searchReset() {
      this.emptyForm();
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    //媒体 logo
    platformLogo(platform) {
      return platformLogo(platform)
    },
    async onLoad(page, params = {}) {
      /*getPlatform().then((res =>{
        this.platformList = res.data.data
        this.option.column[2].dicData = res.data.data*/
      if (!this.loadInitParams) {
        await this.loadDesignerList();
        await this.loadRequesterList();
        //this.query = this.form;
        this.loadInitParams = true;
      }

      this.loading = true;
      this.query.offerType = 'admin,owner,manager,shared';
      await getList(page.currentPage, page.pageSize, Object.assign({}, params, this.query), 'scheduleStatus').then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        data.records.forEach((e) => {
          e.designersList = [];
          if (e.designers) {
            e.designersList = e.designers.split(",")
          }
        });
        this.data = data.records;
        this.loading = false;
      });
    },
    getRowClassName({row, rowIndex}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    // 查找设计师
    findDesigners(val) {
      const users = val
      // 过滤，遍历，拼装成字符串
      return this.allUserList.filter(user => users.includes(user.id)).map(item => item.realName).join(',')
    },
    // marco
    // 打开需求排期新抽屉
    openDistributionDrawer(row) {
      this.distributionDrawer = true
      this.distributionForm.requestId = row.id
      this.distributionForm.name = row.name
      this.distributionForm.designersList = row.designersList
      this.distributionForm.urgency = row.urgency
      this.distributionForm.scheduleDate = row.scheduleDate
    },
    // 保存需求排期分配
    submitDistributionForm() {
      this.SubmitDistributionLoading = true
      this.$refs.distributionFormRef.validate(async valid => {
          if (!valid) return this.SubmitDistributionLoading = false
          try {
            const form = deepClone(this.distributionForm)
            form.designers = form.designersList.join(',')
            delete form.designersList
            const {data: res} = await updateRequsetSchedule(form)
            this.SubmitDistributionLoading = false
            if (res.code !== 200) return this.$message.error('排期/分配保存失败')
            this.$message.success('排期/分配保存成功')
            this.distributionDrawer = false
            this.refreshChange()
          } catch (e) {
            this.SubmitDistributionLoading = false
          }
        }
      )
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量完成
    multipleComplete() {
      this.multipleSelectionId = this.multipleSelection.map(item => item.id)
      console.log(this.multipleSelectionId)
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('批量完成' + this.multipleSelection.length + '条报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await updateScheduleStatusToDoneByBatch(this.multipleSelectionId)
        if (res.code !== 200) return this.$message.error('批量完成失败')
        this.$message.success('批量完成成功')
        this.refreshChange();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },


    // 批量关闭
    multipleClose() {
      this.multipleSelectionId = this.multipleSelection.map(item => item.id)
      console.log(this.multipleSelectionId)
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('批量关闭' + this.multipleSelection.length + '条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await updateDemandStatusToCloseByBatch(this.multipleSelectionId)
        if (res.code !== 200) return this.$message.error('批量关闭失败')
        this.$message.success('批量关闭成功')
        this.refreshChange();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    htmlToString(htmlStr) {
      return htmlStr.replace(/<\/?.+?\/?>|\r|\n|\s*/g, '')
    }
  }
};
</script>

<style lang="scss" scoped>
.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}

// beetles-table{
//   // white-space:pre-wrap
//   // display: inline-block;
//   // white-space: nowrap;
//   // word-break: keep-all;

// }

/deep/ .current-op-row {
  background-color: #f5dab1;
}

.distribution-form {
  padding: 0 15px;
}

.beetles-search-from {
  .el-form-item {
    margin-bottom: unset;

    .el-select {
      width: 100%;
    }
  }
}

</style>
